package a11_单调栈;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * <p>
 * a02_下一个更大元素1复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/3/21
 */
public class a02_下一个更大元素1复习3 {
    public static void main(String[] args) {
        nextGreaterElement(new int[]{1,3,5,2,4}, new int[]{6,5,4,3,2,1,7});
    }

    public static int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] result = new int[nums1.length];
        Arrays.fill(result, -1);

        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            map.put(nums1[i], i);
        }

        Stack<Integer> stack = new Stack<>();
        stack.add(0);

        for (int i = 1; i < nums2.length; i++) {
            while (!stack.isEmpty() && nums2[stack.peek()] < nums2[i]){
                Integer pop = stack.pop();
                if(map.containsKey(nums2[pop])){
                    result[map.get(nums2[pop])] = nums2[i];
                }
            }
            stack.add(i);
        }
        return result;
    }
}
